/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2023-08-31
 * Time: 15:59
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;//根节点


    public TreeNode search(int val){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val<val){
                cur=cur.right;
            }else if(cur.val>val){
                cur=cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }

    //操作-插入
    public boolean insert(int key){
        TreeNode node=new TreeNode(key);
        //如果为空
        if(root==null){
            root=node;
            return true;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.val>key){
                parent=cur;
                cur=cur.left;
            }else{//相等的值不能插入
                return false;
            }
        }
        //判断是插入左边还是右边
        if(parent.val>key){
            parent.left=node;
        }else{
            parent.right=node;
        }
        return true;
    }

    //删除节点
    public void removeNode(int key){
        //先去找这个节点
        TreeNode cur=root;
        TreeNode parent=null;

        while(cur!=null){
            if(cur.val<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.val>key){
                parent=cur;
                cur=cur.left;
            }else{
                remove(cur,parent);
                return;
            }

        }
    }

    private void remove(TreeNode cur, TreeNode parent) {
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }else if(cur==parent.left){
                parent.left=cur.right;
            }else{
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }else if(cur==parent.left){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
        }else{//cur的左右两边均不为空
            //找到右分支最左边的元素target，用它去替换掉要删除的元素，之后再删掉这个target
            //target初始值设定为右边分支的第一个元素
            TreeNode targetParent=cur;
            TreeNode target=cur.right;
            while(target.left!=null){//找右分支最左边的元素
                targetParent=target;
                target=target.left;
            }
            cur.val=target.val;
            if(target==targetParent.left){//targetparent不一定有左分支
                targetParent.left=target.right;
            }else{
                targetParent.right=target.right;
            }
        }
    }
}
